var express = require('express');
var router = express.Router();
const {packRes} = require('../utils/packRes')
const multiparty = require('multiparty')
const {log} = require("debug");
const connection = require('../mysql')
const path = require('path')
const fs = require('fs')
const fullPath = './public/images/article/'



 
router.get('/type', function(req, res, next) {
    connection.query('SELECT * FROM article_type', function(error, results, fields) {
        if (error) throw error;
        res.status(200).send(packRes(200, {results}));
        return;
    });
});

router.post('/type/add', function(req, res, next) {
    const {typename} = req.body;
    connection.query('INSERT INTO article_type (typename) VALUES (?)',
        [typename], function(error, results, fields) {
            if (error) throw error;
            res.status(200).send(packRes(200,{typename}));
            return;
    });
});``
 
router.post('/type/delete/:id', function(req, res, next) {
    const id = req.params.id;
    console.log('删除接口',id)
    connection.query('DELETE FROM article_type WHERE id = ?',[id], function(error, results, fields) {
        if (error) throw error;
        res.status(200).send(packRes(200,'删除成功'));
        return;
    });
});







router.get('/', function(req, res, next) {
    const limit = parseInt(req.query.limit) || 5;
    const page = parseInt(req.query.page) || 1;
    const offset = (page - 1) * limit;
    connection.query('SELECT COUNT(*) as total FROM article', function(error, results, fields) {
        if (error) throw error;
        const total = results[0].total;
        connection.query('SELECT * FROM article LIMIT ?, ?', [offset, limit], function(error, results, fields) {
            if (error) throw error;
            res.status(200).send(packRes(200, {results, total, limit, page}));
            return;
        });
    });
});




router.get('/detail', function(req, res, next) {
    const id = req.query.id;
    connection.query('SELECT * FROM article WHERE id = ?',[id], function(error, results, fields) {
        if (error) throw error;
        res.status(200).send(packRes(200, results[0]));
        return;
    });
});



router.post('/add', function(req, res, next) {
    console.log('8888',req.body,);
    const form = new multiparty.Form();
    form.uploadDir = fullPath;
    form.parse(req,(err,files,file)=>{
        console.log(err,files,file)
        if(err||!file.file[0]){
            res.status(200).send(packRes(400,'','图片上传失败'));
            return;
        }
        console.log('files',files)
        let {article_title:[article_title], article_content:[article_content], typename:[typename]} = files;
        let url = `${req.protocol}://${req.headers.host}${file.file[0].path.replace('public','')}`;
        let currentDate = new Date().toISOString().slice(0, 19).replace('T', ' ');

        console.log(666666,url, article_title, article_content);
        connection.query('INSERT INTO article (url, article_title, article_content, browsecount, likecount, date, typename) VALUES (?, ?, ?, ?, ?, ?, ?)',
            [url, article_title, article_content, 0, 0, currentDate, typename], function(error, results, fields) {
                if (error) throw error;
                res.status(200).send(packRes(200,{ url, article_title, article_content, browsecount:0, likecount:0, date: currentDate, typename }));
                return;
        });
    });
});

router.post('/update', function (req, res, next) {
    const { id,article_title, article_content, typename } = req.body;
    const sql = `SELECT * FROM article WHERE id='${id}'`;
    connection.query(sql,(err,results)=>{
        if (err) throw error;
        if(!results[0]){
            res.status(200).send(packRes(400, null,'找不到该数据'));
        }
        const updateSQL = `UPDATE article SET  article_title = ?, article_content = ?, typename = ? WHERE id = ?`;
        connection.query(updateSQL, [article_title, article_content, typename,id], function (error) {
            console.log(22222222)
            if (error) throw error;
            res.status(200).send(packRes(200, { id, article_title, article_content, typename,url:results[0].url }));
        });
    })
});


router.post('/edit/:id', function(req, res, next) {
    const id = req.params.id;
    const form = new multiparty.Form();
    form.uploadDir = fullPath;
    form.parse(req,(err,files,file)=>{
        if(err){
            res.status(200).send(packRes(400,'','图片上传失败'));
            return;
        }
        let {article_title:[article_title], article_content:[article_content], typename:[typename]} = files;
        let currentDate = new Date().toISOString().slice(0, 19).replace('T', ' ');
        let url = '';
        if(file.file[0]){
            url = `${req.protocol}://${req.headers.host}${file.file[0].path.replace('public','')}`;
            connection.query('SELECT url FROM article WHERE id = ?',[id],function(error, results, fields) {
                if (error) throw error;
                if(results[0].url){
                    let oldPath = path.join(__dirname,`../public${results[0].url.split(req.headers.host)[1]}`);
                    fs.unlink(oldPath, (err) => {
                        if (err) throw err;
                        console.log('原图片已删除');
                    });
                }
            });
        }
        connection.query('UPDATE article SET url = ?, article_title = ?, article_content = ?, typename = ? WHERE id = ?',
            [url, article_title, article_content, typename, id], function(error, results, fields) {
                if (error) throw error;
                res.status(200).send(packRes(200,{ url, article_title, article_content, typename }));
                return;
        });
    });
});
 
router.post('/delete/:id', function(req, res, next) {
    const id = req.params.id;
    connection.query('SELECT url FROM article WHERE id = ?',[id],function(error, results, fields) {
        if (error) throw error;
        if(results[0].url){
            let oldPath = path.join(__dirname,`../public${results[0].url.split(req.headers.host)[1]}`);
            fs.unlink(oldPath, (err) => {
                if (err) throw err;
                console.log('原图片已删除');
            });
        }
    });
    connection.query('DELETE FROM article WHERE id = ?',[id], function(error, results, fields) {
        if (error) throw error;
        res.status(200).send(packRes(200,'删除成功'));
        return;
    });
});

 
router.post('/like/:id', function(req, res, next) {
    const id = req.params.id;
    connection.query('UPDATE article SET likecount = likecount + 1 WHERE id = ?',
        [id], function(error, results, fields) {
            if (error) throw error;
            res.status(200).send(packRes(200,'点赞成功'));
            return;
    });
});

module.exports = router;

